package edu.uts.reekie.designer.actions;

import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IWorkbenchPart;

import edu.uts.reekie.designer.ReekieDesignerPlugin;
import edu.uts.reekie.designer.edit.AbstractConnectorEditPart;
import edu.uts.reekie.designer.edit.ViewNodeEditPart;
import edu.uts.reekie.designer.model.AbstractConnector;
import edu.uts.reekie.designer.model.Multiple;
import edu.uts.reekie.designer.model.ViewNode;

public class ToggleMultiplicityAction extends org.eclipse.gef.ui.actions.SelectionAction {

	public static final String MULTIPLICITY = "Toggle Multiplicity";
	
	Request request;
			
	public ToggleMultiplicityAction(IWorkbenchPart part) {
		super(part);
		
		setText("Toggle Multiplicity");
		setToolTipText("Toggle Multiplicity");
		setId(MULTIPLICITY);
		
		// TODO: change to real icon
		setImageDescriptor(
				ImageDescriptor.createFromFile(ReekieDesignerPlugin.class,"icons/plus.gif")); //$NON-NLS-1$
		
		
		setHoverImageDescriptor(getImageDescriptor());
		

		request = new Request(MULTIPLICITY);
		
	}
	
	protected boolean calculateEnabled() {
		return canPerformAction();
	}


	private boolean canPerformAction() {
		
		if (getSelectedObjects().isEmpty())
			return false;
		
		List<?> parts = getSelectedObjects();
		for (int i=0; i<parts.size(); i++){
			Object o = parts.get(i);
			if (!(o instanceof ViewNodeEditPart))
				return false;
			
			ViewNodeEditPart part = (ViewNodeEditPart)o;
			if (!(part.getModel() instanceof Multiple))
				return false;
			
		}
		return true;
	}
	

	private Command getCommand() {
		
		List editparts = getSelectedObjects();
		CompoundCommand cc = new CompoundCommand();
		cc.setDebugLabel("Toggle Multiplicity");//$NON-NLS-1$
		for (int i=0; i < editparts.size(); i++) {
			ViewNodeEditPart part = (ViewNodeEditPart)editparts.get(i);
			
			ViewNode m = part.getModelAs();
			if (m instanceof Multiple) {
				
				
				cc.add(part.getCommand(request));
			}
			
			
			
		}
		return cc;
	}


	public void run() {
		execute(getCommand());
	}

}
